package com.atguigu.gmall.pay.api;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayConfig;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.feign.order.OrderFeignClient;
import com.atguigu.gmall.model.enums.OrderStatus;

import com.atguigu.gmall.pay.config.AppAliPayConfig;
import com.atguigu.gmall.pay.service.PayService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.sun.org.apache.regexp.internal.RE;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RequestMapping("/api/payment")
@RestController
public class PayListener {

   /* @Autowired
    OrderService orderService;
*/
   @Autowired
   OrderFeignClient orderFeignClient;

   @Autowired
   AppAliPayConfig aliPayConfig;

   @Autowired
   PayService payService;

    /**
     * 支付宝支付成功的异步回调
     * @param vo
     * @param request
     * @return
     */
    @PostMapping("/pay/success/notify")
    public String paySuccess(PayResponseVo vo, HttpServletRequest request) throws AlipayApiException, JsonProcessingException {

        //验证签名
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                aliPayConfig.alipay_public_key,
                aliPayConfig.charset,
                aliPayConfig.sign_type); //调用SDK验证签名

        if (signVerified) {
            System.out.println("验证签名通过.....");
            if (vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")) {
                //支付成功
                // 改订单状态
                orderFeignClient.changeOrderStatusPayed(vo.getOut_trade_no());
                //TODO 发送消息给库存服务,让他减库存
                //vo.getOut_trade_no() 找到对外交易号就知道哪个订单成功了
                payService.sendPaySuccessMessage(vo.getOut_trade_no());
                //TODO 保存支付信息，payment_info

                //orderService.changeOrderStatusPayed(vo.getOut_trade_no(), OrderStatus.PAID.name());
            }

            System.out.println("支付宝带来的数据：" + vo);
            return "success";
        }
        return "88";
    }


}
